<template>
  <base-breadcrumb :title="titleName">
    <searchData
      :search-data="searchArr"
      @search="search"
    />
    <a-card :bordered="false">
      <title-name title="项目列表" />

      <div
        class="table-operator"
        style="margin-top:10px"
      >
        <!--         <a-button type="primary"  @click="handleAdd">新增计划</a-button>-->
      </div>

      <div class="pub-table-select-count">
        <a-icon
          type="info-circle"
          theme="twoTone"
        />
        <span style="margin-right: 12px">
          总计：<span class="totalNum">{{ total || 0 }} 项 </span>
        </span>
      </div>
      <s-table
        ref="table"
        :scroll="{ x: 1500 }"
        size="default"
        :row-key="record=>record.planId"
        :columns="columns"
        :data="loadData"
        :alert="true"
        show-size-changer
        show-quick-jumper
        show-pagination="auto"
      >
        <template
          slot="serial"
          slot-scope="text, record, index"
        >
          {{ index + 1 }}
        </template>
        <template
          slot="statusCode"
          slot-scope="text, record, index"
        >
          <a-badge
            :status="text | statusTypeFilter"
            :text="text | statusFilter"
          />
        </template>
        <template
          slot="action"
          slot-scope="text, record"
        >
          <template>
            <!--           <a @click="handleSub(record)" v-btnPermission="'pm_008_sub_03'">提交审批</a>-->
            <!--            <a-divider type="vertical" v-btnPermission="'pm_008_sub_03'"/>-->
            <a
              v-btnPermission="'pm_008_loo_01'"
              @click="handleView(record,'view')"
            >查看</a>
            <a-divider
              v-if="record.statusCode=='0' || record.statusCode=='3'"
              v-btnPermission="'pm_008_edi_02'"
              type="vertical"
            />
            <a
              v-if="record.statusCode=='0' || record.statusCode=='3'"
              v-btnPermission="'pm_008_edi_02'"
              @click="handleSub(record,'edit')"
            >编辑</a>
            <a-divider
              v-if="record.statusCode=='2' ||record.statusCode=='4' "
              v-btnPermission="'pm_008_imp_04'"
              type="vertical"
            />
            <a
              v-if="record.statusCode=='2' ||record.statusCode=='4' "
              v-btnPermission="'pm_008_imp_04'"
              @click="handleManager(record)"
            >实施管理</a>
            <a-divider
              v-if="record.statusCode && record.statusCode != 0"
              v-btnPermission="'pm_008_moi_05'"
              type="vertical"
            />
            <a
              v-if="record.statusCode && record.statusCode != 0"
              v-btnPermission="'pm_008_moi_05'"
              @click="handleApproveDetail(record)"
            >审批信息</a>
            <!-- <approval-button  :status="record.statusCode" :id="record.planId" ></approval-button> -->
          </template>
        </template>
      </s-table>
    </a-card>

    <a-modal
      :visible="addVisible"
      title="新增施工进度总计划"
      ok-text="确 定 新 增"
      width="900px"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <div style="width:100%">
        <a-form style="margin:20px 0">
          <a-row>
            <a-col
              :md="12"
              :sm="12"
            >
              <a-form-item
                label="项目名称"
                style="display:flex"
                :label-col="{lg: {span: 5}, sm: {span:5}}"
                :wrapper-col="{lg: {span: 17}, sm: {span: 17} }"
              >
                <BaseInput
                  v-model="queryParam.projectName"
                  placeholder=""
                />
              </a-form-item>
            </a-col>
            <a-col
              :md="12"
              :sm="12"
            >
              <a-form-item
                label="项目业态"
                style="display:flex"
                :label-col="{lg: {span: 5}, sm: {span:5}}"
                :wrapper-col="{lg: {span: 17}, sm: {span: 17} }"
              >
                <BaseInput
                  v-model="queryParam.projectName"
                  placeholder=""
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-modal>

    <!--<a-modal v-if="managerVisible" @cancel="managerVisible=false" :visible="true" title="实施管理" width="900px">-->
    <!--<template slot="footer">-->
    <!--<a-button key="back" @click="handleCancels">-->
    <!--取消-->
    <!--</a-button>-->
    <!--</template>-->
    <!--<manager-details/>-->
    <!--</a-modal>-->

    <!-- 审批详情 -->
    <ApprovalDetails
      :title="'审批详情'"
      :business-id="businessId"
      :visible="visibleApprove"
      @cancel="visibleApprove = false"
      @confirm="visibleApprove = false"
    />
  </base-breadcrumb>
</template>

<script>
import Vue from 'vue'
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import { getRoleList, getServiceList } from '@/api/manage'
import { getConstructionProgressList, getTwoImplementation } from '@/api/construction/planInput'
import { getWbsTemplateList } from '@/api/template'
import ARow from 'ant-design-vue/es/grid/Row'
import { getCompany } from '@/api/themeChoose/themeChoose'
import ApprovalDetails from '@/components/approvalDetails'
import managerDetails from '../manager/index'
import SelectSubCompany from '@/components/Select/SelectSubCompany'

const columns = [
  {
    title: '序号',
    width: 65,
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '项目名称',
    dataIndex: 'projectName'
  },
  {
    title: '项目业态',
    dataIndex: 'formatName'
  },
  {
    title: '分公司',
    dataIndex: 'branchName'
  },
  {
    title: '立项时间',
    dataIndex: 'projectCreateTime'
  },
  {
    title: '周期天数(天)',
    width: 120,
    dataIndex: 'duration'
  },
  {
    title: '周期间隔 ',
    dataIndex: 'startTime'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '节点按时完成率',
    dataIndex: 'progress'
  },
  {
    title: '状态 ',
    dataIndex: 'statusCode',
    scopedSlots: { customRender: 'statusCode' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: '180px',
    scopedSlots: { customRender: 'action' }
  }
]

const statusMap = {
  0: { text: '待提交审批', status: 'warning' },
  1: { text: '审批中', status: 'processing' },
  2: { text: '运行中', status: 'success' },
  3: { text: '审批不通过', status: 'error' },
  4: { text: '完工', status: 'success' }
}
export default {
  name: 'a' + Date.now(),
  components: {
    ARow,
    STable,
    ApprovalDetails
  },
  filters: {
    statusFilter(type) {
      return statusMap[type] && statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type] && statusMap[type].status
    }
  },
  data() {
    return {
      columns,
      managerVisible: false,
      projectLevel: false, //是否为项目部层级
      branchLevel: false, //是否为分公司层级
      companyLevel: false, //是否为公司层级

      titleName: '',
      form: {
        projectName: '',
        projectFormat: ''
      },
      // create model
      visible: false,
      businessId: '',
      visibleApprove: false,
      total: {},
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getConstructionProgressList(requestParameters).then((res) => {
          this.total = res.totalSize
          const userInfo = Vue.getAcloudProvider().getUserInfo()
          const code = userInfo?.currentPost?.code
          const setPD = sessionStorage.getItem('setPD')
          // 如果setPD为'done'，说明是用户手动点击关闭的，此时不需要再自动进入实施管理页面
          if (code === 'PD' && setPD !== 'done') {
            const list = res.data || []
            const targetData = list.find((item) => {
              return item.statusCode === '2' || item.statusCode === '4'
            })
            targetData && this.handleManager(targetData, true)
          }
          return res
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      company: [],
      addVisible: false,
      searchArr: [
        // 搜索框
        {
          name: '项目名称',
          value: 'projectName',
          type: 'input'
        },
        {
          name: '项目业态',
          value: 'formatId',
          type: 'select',
          data: []
        },
        {
          name: '分公司',
          valueKey: 'branchId',
          type: SelectSubCompany
        }
      ]
    }
  },
  created() {
    let obj = JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost
    this.branchLevel = obj.code == 'BC' //分公司级
    this.companyLevel = obj.code == 'CO' //公司级
    this.projectLevel = obj.code == 'PD' //项目级

    if (this.branchLevel == true || this.companyLevel == true) {
      this.managerVisible = false
    }

    if (this.projectLevel == true) {
      this.managerVisible = true
    }

    this.getWbsTemplateList()
  },
  methods: {
    handleCancels() {
      this.managerVisible = false
    },
    handleApproveDetail(record) {
      this.visibleApprove = true
      this.businessId = record.planId
    },
    getWbsTemplateList() {
      getWbsTemplateList({ pageNo: 1, pageSize: 2000 }).then((res) => {
        let arr = []
        res.data.forEach((item) => {
          arr.push({
            label: item.formatName,
            value: item.formatId
          })
        })
        this.searchArr[1].data = arr
        console.log(this.searchArr[1].data)
      })
    },
    search(values) {
      this.queryParam = values
      this.$refs.table.refresh(true)
    },
    /**
     * 进入实施管理页面
     * @param {Object} record
     * @param {Boolean} isPD 是否为项目部人员
     */
    handleManager(record, isPD = false) {
      this.$router.push({ path: '/construction/manager', query: { planId: record.planId, isPD: isPD ? 'is' : 'no' } })
    },
    // 分公司
    handleOk() {
      console.log('1')
    },
    handleCancel() {
      this.addVisible = false
    },
    searchData() {
      // 搜索
      this.$refs.table.refresh(true)
    },
    deletes() {},
    handleAdd() {
      this.addVisible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    reset(queryParam) {
      this.queryParam = {}
    },
    handleSub(record, type) {
      localStorage.setItem('currentSelectMasterPlanId', record.planId)
      this.$router.push({
        name: 'staffs',
        query: {
          planId: record.planId,
          projectId: record.projectId,
          type: type
        }
      })
    },
    handleView(record, type) {
      this.$router.push({
        path: '/construction/gantt/view',
        query: {
          planId: record.planId,
          projectId: record.projectId,
          type: type
        }
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
<style scoped>
.ant-modal-body {
  padding: 0;
}
.icon {
  transform: rotate(90deg);
  color: #349ed8;
}
.selects {
  background-color: #e6f3fc;
  box-sizing: border-box;
  border-width: 1px;
  border-style: solid;
  border-color: #d4f0fc;
  border-radius: 4px;
  -moz-box-shadow: none;
  -webkit-box-shadow: none;
  box-shadow: none;
  font-size: 12px;
  text-align: left;
  line-height: 18px;
  padding: 5px 10px;
}
</style>
